package com.gentle.aspect;

import com.gentle.annotation.RedisLockAnnotation;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
/**
 * @author Gentle
 * @date 2019/05/31 : 23:25
 */
@Aspect
@Order(5)
@Component
public class RedisLockAop {
    @Autowired
    RedissonClient redissonClient;


    @Around("@annotation(redisLockAnnotation)")
    public void redisLockHandler(ProceedingJoinPoint joinPoint, RedisLockAnnotation redisLockAnnotation){
        //拿到锁对象
        RLock lock = redissonClient.getLock(redisLockAnnotation.key());
        boolean acquire =false;
        try {
            //尝试加锁
            acquire = lock.tryLock(redisLockAnnotation.time(),redisLockAnnotation.timeunit());
            //成功就执行方法
            if (acquire){
                joinPoint.proceed();
            }
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }finally {
            //拿到锁才释放
            if (acquire){
                lock.unlock();
            }
        }
    }
}
